#!/bin/sh

set -e
#set -x

die() {
	>&2 echo "error: $@"
	exit 1
}

usage() {
	>&2 echo "usage: $0 [OPTIONS] FILENAME"
	>&2 echo
	>&2 echo "options:"
	>&2 echo "   -h|--height  set video height, default is 720"
	>&2 echo "   -265         encode with H.265"
	>&2 echo
	exit 1
}

do_webdlrip() {
	filename="$(basename -- "$FILE")"
	filename="${filename%.*}"

	newname="$filename.mp4"

	audio_params="-c:a aac -b:a 128k"
	if [ "$HEVC" = "1" ]; then
		video_params="-c:v libx265 -crf 27 -preset slow -vtag hvc1 -x265-params no-info=1"
	else
		video_params="-c:v libx264 -preset slow -crf 23 -bsf:v 'filter_units=remove_types=6'"
	fi

	ffmpeg -i "$FILE" \
		-map_metadata -1 -map_chapters -1 \
		-fflags +bitexact -flags:v +bitexact -flags:a +bitexact \
		-metadata:s handler_name='' \
		-metadata:s DURATION='' \
		-metadata:s VENDOR_ID='' \
		-metadata:s encoder='' \
		-empty_hdlr_name 1 \
		$video_params $audio_params \
		-vf sidedata=delete,metadata=delete,scale=-1:$HEIGHT,format=yuv420p \
		"webdlrip_$newname"
	rm "$FILE"
	mv "webdlrip_$newname" "$FILE"
}

[ -z "$1" ] && usage

FILE=
HEIGHT=720

while [ $# -gt 0 ]; do
	case $1 in
		-h|--height)
			HEIGHT="$2"
			shift
			;;
		-265)
			HEVC=1
			;;
		*)
			[ -n "$FILE" ] && die "unexpected argument: $1"
			FILE="$1"
			;;
	esac
	shift
done

[ -z "$FILE" ] && usage
[ -f "$FILE" ] || die "$FILE: file not found"

echo "filename: $FILE"
echo "  height: $HEIGHT"
echo

do_webdlrip
